package com.novatialabs.qttt.gwt.client;

import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.event.shared.HandlerRegistration;

public class GameController implements MarkHandler, HasGameDisplayHandlers {

  private final HandlerManager handlerManager = new HandlerManager(this);
  private GameModel game;
  private Notation urlNotation = new UrlNotation();
  private final ValueChangeHandler<String> historyChangeHandler = new ValueChangeHandler<String>() {

    public void onValueChange(ValueChangeEvent<String> event) {
      String gameString = event.getValue();
      setGameStateFromHistoryToken(gameString);
    }
  };

  public GameController(GameModel game) {
    this.game = game;
  }

  protected void setGameStateFromHistoryToken(String gameString) {
    game = urlNotation.parseGame(gameString);
    fireEvent(new GameDisplayEvent(game));
  }

  public String getGameStateHistoryToken() {
    return urlNotation.printGame(game);
  }

  public void onMark(MarkEvent event) {
    mark(event.getCellNumber());

  }

  private void mark(int cellNumber) {
    game.mark(cellNumber);
    fireEvent(new GameDisplayEvent(game));

  }

  public HandlerRegistration addGameDisplayHandler(GameDisplayHandler handler) {
    return handlerManager.addHandler(GameDisplayEvent.getType(), handler);
  }

  public void fireEvent(GwtEvent<?> event) {
    // Normally Widget handles this.
    handlerManager.fireEvent(event);
  }

  public ValueChangeHandler<String> getHistoryChangeHandler() {

    return historyChangeHandler;
  }

}
